#include "qae_qansipalette.h"
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
#include <QtCore/QDebug>


namespace QAnsiEditor {


QAnsiPalette::QAnsiPalette(QWidget *parent)
    : QWidget(parent), m_iForeIndex(8), m_iBackIndex(0)
{
    setMinimumSize(200, 40);
    setMaximumSize(300, 60);
}

QSize QAnsiPalette::sizeHint() const
{
    return QSize(200, 40);
}

QColor QAnsiPalette::ansiColor(int index)
{
    static QColor arrAnsiColors[16] = {
        Qt::black,
        Qt::darkRed,
        Qt::darkGreen,
        Qt::darkYellow,
        Qt::darkBlue,
        Qt::darkMagenta,
        Qt::darkCyan,
        Qt::gray,
        Qt::darkGray,
        Qt::red,
        Qt::green,
        Qt::yellow,
        Qt::blue,
        Qt::magenta,
        Qt::cyan,
        Qt::white
    };

    return arrAnsiColors[index];
}

void QAnsiPalette::paintEvent(QPaintEvent *pe)
{
    int iStart = size().height();
    int iPenWidth = 2;
    int iWidth = (width()-iStart) / 8;
    int iHeight = height() / 2;

    QPainter painter(this);
    QPen blackPen(QBrush(Qt::black), iPenWidth);
    painter.setPen(blackPen);
    // dark colors
    for (int i = 0; i < 8; i++) {
        QRect r(iStart+i*iWidth, 0, iWidth, iHeight);
        painter.fillRect(r, QAnsiPalette::ansiColor(i));
        r.adjust(-iPenWidth/2, iPenWidth/2, -iPenWidth/2, -iPenWidth/2);
        painter.drawRect(r);
    }
    // light colors
    for (int i = 8; i < 16; i++) {
        QRect r(iStart+(i-8)*iWidth, iHeight, iWidth, iHeight);
        painter.fillRect(r, QAnsiPalette::ansiColor(i));
        r.adjust(-iPenWidth/2, -iPenWidth/2, -iPenWidth/2, -iPenWidth/2);
        painter.drawRect(r);
    }
    painter.drawRect(iPenWidth/2, iPenWidth/2, iStart-iPenWidth, height()-iPenWidth);
    // sample display
    int iPadding = height() / 8;
    int iPadding2 = iPadding * 2;
    QRect br(iPadding, iPadding, height()-iPadding-iPadding2, height()-iPadding-iPadding2);
    QRect fr(iPadding2, iPadding2, height()-iPadding-iPadding2, height()-iPadding-iPadding2);
    painter.fillRect(br, QAnsiPalette::ansiColor(m_iBackIndex));
    painter.fillRect(fr, QAnsiPalette::ansiColor(m_iForeIndex));
}

void QAnsiPalette::mouseReleaseEvent(QMouseEvent *me) {
    int iStart = size().height();
    int iWidth = (width()-iStart) / 8;

    QPoint pt = me->pos();
    if (me->button() == Qt::LeftButton) {
        if (pt.y() <= height() / 2) {
            m_iForeIndex = (pt.x()-iStart) / iWidth;
        } else {
            m_iForeIndex = (pt.x()-iStart) / iWidth + 8;
        }
    } else if (me->button() == Qt::RightButton) {
        m_iBackIndex = (pt.x()-iStart) / iWidth;
    }

    char chColor = m_iForeIndex | (m_iBackIndex << 4);
    emit colorChanged(chColor);
    update();
}


}  // namespace QAnsiEditor
